package com.tju.ocean_ecology_website.controller;

import com.tju.ocean_ecology_website.dto.ApiResponse;
import com.tju.ocean_ecology_website.dto.PageResult;
import com.tju.ocean_ecology_website.dto.ProjectParticipantDTO;
import com.tju.ocean_ecology_website.dto.ProjectQueryDTO;
import com.tju.ocean_ecology_website.dto.ProjectRejectDTO;
import com.tju.ocean_ecology_website.entity.Activity;
import com.tju.ocean_ecology_website.entity.ActivitySignup;
import com.tju.ocean_ecology_website.entity.User;
import com.tju.ocean_ecology_website.service.ActivityService;
import com.tju.ocean_ecology_website.service.ActivitySignupService;
import com.tju.ocean_ecology_website.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 志愿项目管理控制器
 */
@RestController
@RequestMapping("api")
public class ProjectController {

    @Autowired
    private ActivityService activityService;
    
    @Autowired
    private ActivitySignupService activitySignupService;
    
    @Autowired
    private UserService userService;

    /**
     * 获取志愿项目列表
     *
     * @param queryDTO 查询参数
     * @return 志愿项目列表
     */
    @GetMapping("/projects")
    public ResponseEntity<ApiResponse<PageResult<Activity>>> getProjectList(ProjectQueryDTO queryDTO) {
        // 创建活动筛选条件
        Activity activityQuery = new Activity();
        if (queryDTO.getTitle() != null && !queryDTO.getTitle().isEmpty()) {
            activityQuery.setTitle(queryDTO.getTitle());
        }
        if (queryDTO.getStatus() != null) {
            activityQuery.setStatus(queryDTO.getStatus());
        }
        if (queryDTO.getAuditStatus() != null) {
            activityQuery.setAuditStatus(queryDTO.getAuditStatus());
        }
        if (queryDTO.getOrganizationId() != null) {
            activityQuery.setOrganizationId(queryDTO.getOrganizationId());
        }
        
        // 查询活动数据
        PageRequest pageRequest = queryDTO.toPageRequest();
        Page<Activity> activityPage = activityService.queryByPage(activityQuery, pageRequest);
        
        // 创建分页结果
        PageResult<Activity> pageResult = PageResult.fromPage(activityPage, queryDTO.getPage());
        
        return ResponseEntity.ok(ApiResponse.success(pageResult));
    }

    /**
     * 获取志愿项目详情
     *
     * @param id 项目ID
     * @return 项目详情
     */
    @GetMapping("/projects/{id}")
    public ResponseEntity<ApiResponse<Activity>> getProjectDetail(@PathVariable("id") Long id) {
        Activity activity = activityService.queryById(id);
        if (activity == null) {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "项目不存在"));
        }
        
        return ResponseEntity.ok(ApiResponse.success(activity));
    }

    /**
     * 添加志愿项目
     *
     * @param activity 项目信息
     * @return 添加结果
     */
    @PostMapping("/projects")
    public ResponseEntity<ApiResponse<Activity>> addProject(@RequestBody Activity activity) {
        // 设置默认值
        activity.setAuditStatus(0); // 待审核
        activity.setCurrentParticipants(0); // 当前参与人数为0
        activity.setCreateTime(new Date());
        activity.setUpdateTime(new Date());
        
        Activity savedActivity = activityService.insert(activity);
        
        return ResponseEntity.ok(ApiResponse.success(savedActivity, "添加项目成功"));
    }

    /**
     * 更新志愿项目
     *
     * @param id 项目ID
     * @param activity 项目信息
     * @return 更新结果
     */
    @PutMapping("/projects/{id}")
    public ResponseEntity<ApiResponse<Activity>> updateProject(
            @PathVariable("id") Long id,
            @RequestBody Activity activity) {
        
        // 查询项目信息
        Activity existingActivity = activityService.queryById(id);
        if (existingActivity == null) {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "项目不存在"));
        }
        
        // 设置ID和更新时间
        activity.setId(id);
        activity.setUpdateTime(new Date());
        
        // 保留原有的审核状态和拒绝原因
        activity.setAuditStatus(existingActivity.getAuditStatus());
        activity.setRejectReason(existingActivity.getRejectReason());
        
        // 更新项目
        Activity updatedActivity = activityService.update(activity);
        
        return ResponseEntity.ok(ApiResponse.success(updatedActivity, "更新项目成功"));
    }

    /**
     * 删除志愿项目
     *
     * @param id 项目ID
     * @return 删除结果
     */
    @DeleteMapping("/projects/{id}")
    public ResponseEntity<ApiResponse<Boolean>> deleteProject(@PathVariable("id") Long id) {
        // 查询项目信息
        Activity activity = activityService.queryById(id);
        if (activity == null) {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "项目不存在"));
        }
        
        // 删除项目
        boolean result = activityService.deleteById(id);
        
        return ResponseEntity.ok(ApiResponse.success(result, result ? "删除项目成功" : "删除项目失败"));
    }

    /**
     * 审核通过项目
     *
     * @param id 项目ID
     * @return 审核结果
     */
    @PostMapping("/projects/{id}/approve")
    public ResponseEntity<ApiResponse<Activity>> approveProject(@PathVariable("id") Long id) {
        // 查询项目信息
        Activity activity = activityService.queryById(id);
        if (activity == null) {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "项目不存在"));
        }
        
        // 更新审核状态
        activity.setAuditStatus(1); // 已通过
        activity.setRejectReason(null); // 清空拒绝原因
        activity.setUpdateTime(new Date());
        
        // 更新项目
        Activity updatedActivity = activityService.update(activity);
        
        return ResponseEntity.ok(ApiResponse.success(updatedActivity, "审核通过成功"));
    }

    /**
     * 拒绝项目
     *
     * @param id 项目ID
     * @param rejectDTO 拒绝信息
     * @return 拒绝结果
     */
    @PostMapping("/projects/{id}/reject")
    public ResponseEntity<ApiResponse<Activity>> rejectProject(
            @PathVariable("id") Long id,
            @Valid @RequestBody ProjectRejectDTO rejectDTO) {
        
        // 查询项目信息
        Activity activity = activityService.queryById(id);
        if (activity == null) {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "项目不存在"));
        }
        
        // 更新审核状态
        activity.setAuditStatus(2); // 已拒绝
        activity.setRejectReason(rejectDTO.getReason()); // 设置拒绝原因
        activity.setUpdateTime(new Date());
        
        // 更新项目
        Activity updatedActivity = activityService.update(activity);
        
        return ResponseEntity.ok(ApiResponse.success(updatedActivity, "拒绝项目成功"));
    }

    /**
     * 获取项目参与者
     *
     * @param id 项目ID
     * @param page 页码
     * @param pageSize 每页大小
     * @return 参与者列表
     */
    @GetMapping("/projects/{id}/participants")
    public ResponseEntity<ApiResponse<PageResult<ProjectParticipantDTO>>> getProjectParticipants(
            @PathVariable("id") Long id,
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        
        // 查询项目信息
        Activity activity = activityService.queryById(id);
        if (activity == null) {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "项目不存在"));
        }
        
        // 查询报名信息
        ActivitySignup signupQuery = new ActivitySignup();
        signupQuery.setActivityId(id);
        
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize);
        Page<ActivitySignup> signupPage = activitySignupService.queryByPage(signupQuery, pageRequest);
        
        // 构建参与者DTO列表
        List<ProjectParticipantDTO> participantDTOs = new ArrayList<>();
        for (ActivitySignup signup : signupPage.getContent()) {
            // 查询用户信息
            User user = userService.queryById(signup.getUserId());
            
            // 构建DTO
            ProjectParticipantDTO dto = ProjectParticipantDTO.fromUserAndSignup(user, signup);
            participantDTOs.add(dto);
        }
        
        // 创建分页结果
        Page<ProjectParticipantDTO> dtoPage = new PageImpl<>(participantDTOs, pageRequest, signupPage.getTotalElements());
        PageResult<ProjectParticipantDTO> pageResult = PageResult.fromPage(dtoPage, page);
        
        return ResponseEntity.ok(ApiResponse.success(pageResult));
    }
}
